package com.genersoft.iot.vmp.baidu;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.FaceVerifyRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;

public class BaiduFaceApi {

    //设置APPID/AK/SK
    public static final String APP_ID = "44358684";
    public static final String API_KEY = "GjGQbp2QjKyGeTz8lniuTgQC";
    public static final String SECRET_KEY = "PeY5kGsIfYOmNtp9qUl7NQRFeoxAM7zD";
    public static final String APP_GROUP ="wogou";

    private static final Logger logger = LoggerFactory.getLogger(BaiduFaceApi.class);

    /**
     * 新增人脸数据
     * @param userId 指定用户ID
     * @param image 人脸底图
     * @param imageType 底图数据类型 BASE64,URL,FACE_TOKEN
     */
    public static String addUser(String userId,String image,String imageType){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");

        // 人脸注册
        JSONObject res = client.addUser(image, imageType, APP_GROUP, userId, options);
        try {
            return res.getString("face_token");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新人脸数据
     * @param userId 指定用户ID
     * @param image 人脸底图
     * @param imageType 底图数据类型 BASE64,URL,FACE_TOKEN
     */
    public static String updateUser(String userId,String image,String imageType){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");

        // 人脸更新
        JSONObject res = client.updateUser(image, imageType, APP_GROUP, userId, options);
        try {
            return res.getString("face_token");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 删除用户
     * @param userId 指定用户ID
     */
    public static Boolean deleteUser(String userId){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        // 删除用户
        JSONObject res = client.deleteUser(APP_GROUP, userId, options);

        try {
            if (res.getInt("error_code") ==0){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 人脸搜索
     * @param image 图片
     * @param imageType 图片类型 BASE64 URL FACE_TOKEN
     */
    public static Set<String> multiSearch(String image,String imageType) {
        Set<String> list = new HashSet<>();
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("max_face_num", "10");
        options.put("match_threshold", "70");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "3");

        // 人脸检测
        JSONObject res = client.multiSearch(image, imageType, APP_GROUP, options);
        System.out.println(res);
        try {
            if (res.getInt("error_code") ==0){
                JSONObject result = res.getJSONObject("result");

                JSONArray faceList = result.getJSONArray("face_list");
                for (int i = 0; i < faceList.length(); i++) {
                    JSONArray userList = faceList.getJSONObject(i).getJSONArray("user_list");
                    for (int j = 0; j < userList.length(); j++) {
                        list.add(userList.getJSONObject(j).getString("user_id"));
                    }
                }

            }
            if (res.getInt("error_code") == 222207){
                list.add("未知人员");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 活体检测
     * @param image 图片
     * @param imageType 图片类型 BASE64 URL FACE_TOKEN
     */
    public static void faceverify(String image,String imageType){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        FaceVerifyRequest req = new FaceVerifyRequest(image, imageType);
        ArrayList<FaceVerifyRequest> list = new ArrayList<FaceVerifyRequest>();
        list.add(req);
        JSONObject res = client.faceverify(list);
        System.out.println(res);
    }


    /**
     * 视频活体验证
     * @param video 视频路径
     */
    public static Set<String> videoFaceliveness(String video){
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        String targetPath ="face";
        File snapFolder = new File(targetPath);
        if (!snapFolder.exists()) {
            if (!snapFolder.mkdirs()) {
                logger.warn("{}路径创建失败", snapFolder.getAbsolutePath());
            }
        }
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        String sessionId="";
        JSONObject res = client.videoFaceliveness(sessionId, video, options);
        Set<String> userList = new HashSet<>();
        try {
            if (res.getInt("err_no") ==0){
                List<String> list = new ArrayList<>();
                JSONObject result = res.getJSONObject("result");
                JSONArray picList = result.getJSONArray("pic_list");
                for (int i = 0; i < picList.length(); i++) {
                    if (!list.contains(picList.getJSONObject(i).getString("face_token"))){
                        list.add(picList.getJSONObject(i).getString("pic"));
                        Base64Util.baseToFile(picList.getJSONObject(i).getString("pic"),targetPath + File.separator +picList.getJSONObject(i).getString("face_token")+".jpg");
                    }
                }
                if (list.size()>0){
                    for (String pic: list) {
                        Set<String> base64 = multiSearch(pic, "BASE64");
                        userList.addAll(base64);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return userList;
    }


    public static void main(String[] args) {
        multiSearch(Base64Util.fileToBase64("D:\\Project\\wvp-gb28181-talk-demo\\video\\1702890624101.jpg"), "BASE64");
    }
}
